import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Layout from '@/layouts/Layout.vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { isTokenExpired } from '@/utils/token'
import { showErrorMessage } from '@/utils/message'

const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: {
            title: '登录',
            hideInMenu: true,
        },
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: {
            title: '数据大屏',
            icon: 'TrendCharts',
            requiresAuth: true,
            permission: 'super_admin', // 只有超级管理员才能访问
            hideInMenu: true, // 不在侧边栏菜单中显示
        },
    },
    {
        path: '/',
        component: Layout,
        redirect: '/home',
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import('@/views/Home.vue'),
                meta: {
                    title: '首页',
                    icon: 'HomeFilled',
                    requiresAuth: true,
                    // 首页不需要特定权限，所有登录用户都可以访问
                },
            },
        ],
    },
    {
        path: '/doctor',
        component: Layout,
        redirect: '/doctor/list',
        meta: {
            title: '医生管理',
            icon: 'User',
            requiresAuth: true,
            permission: 'doctor',
        },
        children: [
            {
                path: 'list',
                name: 'DoctorList',
                component: () => import('@/views/doctor/DoctorList.vue'),
                meta: {
                    title: '医生列表',
                    icon: 'UserFilled',
                    requiresAuth: true,
                    permission: 'doctor:list',
                },
            },
            {
                path: 'schedule',
                name: 'DoctorSchedule',
                component: () => import('@/views/doctor/DoctorSchedule.vue'),
                meta: {
                    title: '医生排班',
                    icon: 'Calendar',
                    requiresAuth: true,
                    permission: 'doctor:schedule',
                },
            },
        ],
    },
    {
        path: '/patient',
        component: Layout,
        redirect: '/patient/list',
        meta: {
            title: '患者管理',
            icon: 'Avatar',
            requiresAuth: true,
            permission: 'patient',
        },
        children: [
            {
                path: 'list',
                name: 'PatientList',
                component: () => import('@/views/patient/PatientList.vue'),
                meta: {
                    title: '患者列表',
                    icon: 'UserFilled',
                    requiresAuth: true,
                    permission: 'patient:list',
                },
            },
            {
                path: 'records',
                name: 'MedicalRecords',
                component: () => import('@/views/patient/MedicalRecords.vue'),
                meta: {
                    title: '病历管理',
                    icon: 'Document',
                    requiresAuth: true,
                    permission: 'patient:records',
                },
            },
        ],
    },
    {
        path: '/appointment',
        component: Layout,
        redirect: '/appointment/list',
        meta: {
            title: '预约管理',
            icon: 'Calendar',
            requiresAuth: true,
            permission: 'appointment',
        },
        children: [
            {
                path: 'list',
                name: 'AppointmentList',
                component: () => import('@/views/appointment/AppointmentList.vue'),
                meta: {
                    title: '预约列表',
                    icon: 'List',
                    requiresAuth: true,
                    permission: 'appointment:list',
                },
            },
            {
                path: 'calendar',
                name: 'AppointmentCalendar',
                component: () => import('@/views/appointment/AppointmentCalendar.vue'),
                meta: {
                    title: '预约日历',
                    icon: 'Calendar',
                    requiresAuth: true,
                    permission: 'appointment:calendar',
                },
            },
        ],
    },
    {
        path: '/finance',
        component: Layout,
        redirect: '/finance/billing',
        meta: {
            title: '财务管理',
            icon: 'Money',
            requiresAuth: true,
            permission: 'finance',
        },
        children: [
            {
                path: 'billing',
                name: 'Billing',
                component: () => import('@/views/finance/Billing.vue'),
                meta: {
                    title: '账单管理',
                    icon: 'Tickets',
                    requiresAuth: true,
                    permission: 'finance:billing',
                },
            },
            {
                path: 'statistics',
                name: 'FinanceStatistics',
                component: () => import('@/views/finance/Statistics.vue'),
                meta: {
                    title: '财务统计',
                    icon: 'TrendCharts',
                    requiresAuth: true,
                    permission: 'finance:statistics',
                },
            },
        ],
    },
    {
        path: '/datalist',
        component: Layout,
        redirect: '/datalist/ai',
        meta: {
            title: '数据管理',
            icon: 'PieChart',
            requiresAuth: true,
            permission: 'system',
        },
        children: [
            {
                path: 'ai',
                name: 'Ai',
                component: () => import('@/views/datalist/Ai.vue'),
                meta: {
                    title: '魔镜数据管理',
                    icon: 'Camera',
                    requiresAuth: true,
                    permission: 'system:user',
                },
            },
            {
                path: 'product',
                name: 'Product',
                component: () => import('@/views/datalist/Product.vue'),
                meta: {
                    title: '产品管理',
                    icon: 'Box',
                    requiresAuth: true,
                    permission: 'system:role',
                },
            },
            {
                path: 'organization',
                name: 'Organization',
                component: () => import('@/views/datalist/Organization.vue'),
                meta: {
                    title: '机构管理',
                    icon: 'OfficeBuilding',
                    requiresAuth: true,
                    permission: 'system:permission',
                },
            },
        ],
    },
    {
        path: '/system',
        component: Layout,
        redirect: '/system/users',
        meta: {
            title: '系统管理',
            icon: 'Setting',
            requiresAuth: true,
            permission: 'system',
        },
        children: [
            {
                path: 'users',
                name: 'SystemUsers',
                component: () => import('@/views/system/Users.vue'),
                meta: {
                    title: '用户管理',
                    icon: 'User',
                    requiresAuth: true,
                    permission: 'system:user',
                },
            },
            {
                path: 'roles',
                name: 'SystemRoles',
                component: () => import('@/views/system/Roles.vue'),
                meta: {
                    title: '角色管理',
                    icon: 'Avatar',
                    requiresAuth: true,
                    permission: 'system:role',
                },
            },
            {
                path: 'settings',
                name: 'SystemSettings',
                component: () => import('@/views/system/Settings.vue'),
                meta: {
                    title: '系统设置',
                    icon: 'Tools',
                    requiresAuth: true,
                    permission: 'system:permission',
                },
            },
        ],
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    // 设置页面标题
    document.title = to.meta?.title ? `${to.meta.title} - 互联网医院管理平台` : '互联网医院管理平台'

    // 检查双token登录状态
    const accessToken = localStorage.getItem('hospital-access-token')
    const refreshToken = localStorage.getItem('hospital-refresh-token')
    const hasValidToken = accessToken && refreshToken

    // 如果没有token且不是访问登录页，跳转到登录页
    if (to.path !== '/login' && !hasValidToken) {
        next('/login')
        return
    }

    // 如果有token，验证token有效性
    if (hasValidToken) {
        try {
            // 验证access token是否过期
            if (accessToken) {
                const isAccessTokenExpired = isTokenExpired(accessToken)

                // 如果access token已过期
                if (isAccessTokenExpired) {
                    // 验证refresh token是否也过期
                    const isRefreshTokenExpired = isTokenExpired(refreshToken)

                    if (isRefreshTokenExpired) {
                        // 两个token都过期，清除登录状态并跳转登录页
                        const userStore = useUserStore()
                        userStore.logout()
                        showErrorMessage('登录已过期，请重新登录')
                        next('/login')
                        return
                    } else {
                        // refresh token未过期，但access token过期
                        // 尝试自动刷新token
                        try {
                            const userStore = useUserStore()
                            const response: any = await request({
                                url: '/jjx/refresh-token',
                                method: 'POST',
                                data: {
                                    refreshToken: refreshToken
                                }
                            })

                            if (response.success) {
                                // 刷新成功，更新token
                                userStore.setTokens(
                                    response.data.accessToken,
                                    response.data.refreshToken
                                )
                                // 继续导航
                                next()
                                return
                            } else {
                                throw new Error('Token刷新失败')
                            }
                        } catch (refreshError) {
                            // 刷新失败，清除登录状态
                            const userStore = useUserStore()
                            userStore.logout()
                            showErrorMessage('登录已过期，请重新登录')
                            next('/login')
                            return
                        }
                    }
                }
            }

            // 如果已经登录且访问登录页，跳转到首页
            if (to.path === '/login') {
                next('/')
                return
            }
        } catch (error) {
            // token解析失败，清除登录状态
            const userStore = useUserStore()
            userStore.logout()
            showErrorMessage('登录状态异常，请重新登录')
            next('/login')
            return
        }
    }

    // 检查权限（仅对需要权限的路由）
    if (to.meta?.requiresAuth && to.meta?.permission) {
        const userStore = useUserStore()

        // 如果用户信息不存在，说明刚刷新页面，让其继续（会在Layout中重新获取用户信息）
        if (!userStore.userInfo) {
            next()
            return
        }

        const requiredPermission = to.meta.permission as string

        // 特殊处理超级管理员权限
        if (requiredPermission === 'super_admin') {
            if (!userStore.isSuperAdmin) {
                ElMessage.error('此页面仅限超级管理员访问')
                // 跳转到首页或者上一页
                if (from.path !== '/login') {
                    next(from.path)
                } else {
                    next('/home')
                }
                return
            }
            next()
            return
        }

        // 超级管理员拥有所有其他权限
        if (userStore.isSuperAdmin) {
            next()
            return
        }

        // 检查是否有对应权限
        if (!userStore.hasPermission(requiredPermission)) {
            ElMessage.error('您没有访问该页面的权限')
            // 跳转到首页或者上一页
            if (from.path !== '/login') {
                next(from.path)
            } else {
                next('/home')
            }
            return
        }
    }

    next()
})

export default router